<template>
	<!-- 父组件要引入登录弹窗，因为分享海报要登录 -->
	<view :style="{ '--color': vuex_config.themeColor1 }">
		<view class="sww-sidebar-box" :style="[
				{
					bottom: bottom + 'rpx',
					right: right + 'rpx',
				},
				customStyle
			]" v-if="sidebarBox">
			<button class="sww-sidebar-item u-reset-button" v-if="opacity == 1" @click="$backToTop">
				<u-icon name="e69e" size="40" custom-prefix="iconfont"></u-icon>
			</button>
			<!-- #ifndef APP-PLUS  || MP-BAIDU -->
			<button v-if="share" class="sww-sidebar-item u-reset-button" @click="$showSelectBox">
				<u-icon name="e6eb" size="40" custom-prefix="iconfont"></u-icon>
			</button>
			<!-- #endif -->

			<!-- #ifdef MP-WEIXIN || MP-BAIDU -->
			<button v-if="contact" class="sww-sidebar-item u-reset-button" open-type="contact" @click="$customer">
				<u-icon name="e741" size="40" custom-prefix="iconfont"></u-icon>
			</button>
			<!-- #endif -->
		</view>
		<u-mask :show="shareVisible" z-index="100" :zoom="false" @click="$closePopup">
			<view class="h5-show-tips">请点击分享</view>
		</u-mask>
		<!-- 分享选择弹框， 分享微信好友或生成海报-->
		<u-popup v-model="shareBoxVisible" mode="bottom" z-index="100" safe-area-inset-bottom border-radius="16">
			<view class="share-select-box">
				<view class="share-select-list">

					<!-- #ifndef MP-ALIPAY || MP-BAIDU	 -->
					<button class="share-select-item u-reset-button" open-type="share" @click="$share">
						<u-icon name="weixin-fill" class="share-select-icon"></u-icon>
						<view class="share-select-text">微信好友</view>
					</button>
					<!-- #endif  -->

					<!-- #ifdef MP-ALIPAY  -->
					<button class="share-select-item u-reset-button" open-type="share" @click="$share">
						<u-icon name="e60b" class="share-select-icon" custom-prefix="iconfont"></u-icon>
						<view class="share-select-text">分享好友</view>
					</button>
					<!-- #endif  -->

					<!-- #ifdef MP-BAIDU  -->
					<button class="share-select-item u-reset-button" open-type="share" @click="$share">
						<u-icon name="e8cb" class="share-select-icon" color="#ffffff" custom-prefix="iconfont"></u-icon>
						<view class="share-select-text">分享好友</view>
					</button>
					<!-- #endif  -->

					<button class="share-select-item u-reset-button" @click="$createPoster" v-if="sidebarBox">
						<u-icon name="moments" class="share-select-icon"></u-icon>
						<view class="share-select-text">生成海报</view>
					</button>
				</view>
				<view class="share-select-cancel" @click="shareBoxVisible = false">取消</view>
			</view>
		</u-popup>
		<!--    产品海报，暂时显示后端返回的二维码或海报，待优化-->
		<u-mask :show="posterVisible" z-index="100" :zoom="false" @click="$closePopup" :custom-style="posterStyle">

			<!-- #ifndef  MP-ALIPAY -->
			<canvas style="width: 375px; position: absolute; left: 750rpx; height: 2500rpx;  opacity: 0;"
				canvas-id="codecanvas" />
			<view class="post_main">
				<view class="poster-box" @click.stop.prevent v-if="posterUrl">
					<image class="poster-img" :src="posterUrl" mode="widthFix" show-menu-by-longpress></image>
					<view class="poster-text">长按保存图片到手机相册</view>
				</view>
			</view>
			<!--  #endif -->

			<!-- #ifdef   MP-ALIPAY -->
			<canvas style="width: 375px; position: absolute; left: 750rpx; height: 2500rpx;  opacity: 0;"
				id="codecanvas" />
			<view class="post_main">
				<view class="poster-box" @click.stop.prevent v-if="posterUrl">
					<image class="poster-img" :src="posterUrl" mode="widthFix" @click="saveImageToPhotosAlbum"></image>
					<view class="poster-text">点击保存图片到手机相册</view>
				</view>
			</view>
			<!--  #endif -->


		</u-mask>
	</view>
</template>
<script>
	import {
		mapState
	} from 'vuex';
	import {
		uniModal,
		uniCall,
		uniGetImageInfo
	} from '../../utils/uniPromise';
	import UMask from '../../uview-ui/components/u-mask/u-mask';
	export default {
		components: {
			UMask
		},
		props: {
			// 返回顶部滚动时间
			duration: {
				type: [Number, String],
				default: 100
			},
			// 是否显示盒子
			sidebarBox: {
				type: Boolean,
				default: true
			},
			// 滚动距离
			scrollTop: {
				type: [Number, String],
				default: 0
			},
			// 距离顶部多少距离显示，单位rpx
			top: {
				type: [Number, String],
				default: 400
			},
			right: {
				// 距离右侧距离，单位rpx
				type: [String, Number],
				default: 24
			},
			bottom: {
				// 距离底部距离，单位rpx
				type: [String, Number],
				default: 292
			},
			// 整个组件的样式
			customStyle: {
				type: Object,
				default () {
					return {};
				}
			},
			// 是否显示分享按钮
			share: {
				type: Boolean,
				default: false
			},
			// 是否显示客服按钮
			hasTop:{
				type:Boolean,
				default:true
			}, // 是否有返回顶部的按钮
			contact: {
				type: Boolean,
				default: false
			},
			// 产品信息，需要分享海报功能时传入此参数
			prodInfo: {
				type: Object
			},
			stockName:{
				type:String,
				default:'product_stock'
			},// 规格字段名
		},
		data() {
			return {
				// 不透明度，为了让组件有一个显示和隐藏的过渡动画
				opacity: 0,
				// 组件的z-index值，隐藏时设置为-1，就会看不到
				shareVisible: false,
				shareBoxVisible: false,
				posterVisible: false,
				productimgform: {}, //产品图片信息
				codeimgform: {}, //二维码图片信息
				posterUrl: '',
				posterStyle: {
					display: 'flex',
					alignItems: 'center',
					justifyContent: 'center'
				}
			};
		},
		computed: {
			...mapState(['vuex_business', 'vuex_user', 'vuex_businessObj']),
			showBackTop() {
				// 由于scrollTop为页面的滚动距离，默认为px单位，这里将用于传入的top(rpx)值
				// 转为px用于比较，如果滚动条到顶的距离大于设定的距离，就显示返回顶部的按钮
				if(this.hasTop){
					return this.scrollTop > uni.upx2px(this.top);
				}else{
					return false
				}
			},
			//参数海报参数
			posterParams() {
				if (this.prodInfo && this.prodInfo.pk_id) {
					let params = {
						product_id: this.prodInfo.pk_id,
						type: '',
						url: ''
					};
					if (this.prodInfo.prodType == 1) {
						// 普通产品
						params.url = '/package/product/local/prod/index';
						params.type = 5;
					} else if (this.prodInfo.prodType == 2) {
						// 门票
						params.url = '/package/product/ticket/prod/index';
						params.type = 1;
						this.prodInfo.logo = this.prodInfo.img ? this.prodInfo.img.split(',')[0] : this.vuex_business.logo
					} else if (this.prodInfo.prodType == 3) {
						// 酒店
						params.url = '/package/hotel/reserve/details/index';
						params.type = 2;
						this.prodInfo.logo = this.prodInfo.poster_url
					} else if (this.prodInfo.prodType == 4) {
						// 拍卖
						params.url = '/package/product/dutchAuction/index';
						params.type = 5;
					} else if (this.prodInfo.prodType == 5) {
						// 线路
						params.url = '/package/line/detail/index';
						this.prodInfo.logo = this.prodInfo.img ? this.prodInfo.img.split(',')[0] : this.vuex_business.logo
						params.type = 3;
					}else if(this.prodInfo.prodType == 12){
						// 分红
						params.url = '/package/product/bonusProd/detail';
						this.prodInfo.logo = this.prodInfo.img ? this.prodInfo.img.split(',')[0] : this.vuex_business.logo
						params.type = 12;
					} else {
						params.url = '/package/product/local/prod/index';
					}
					// #ifdef H5
					params.url = window.location.origin + params.url;
					// #endif
					if (params) {
						//给链接添加产品id，分销id
						params.url = `${params.url}?id=${this.prodInfo.pk_id}`;

						// #ifdef  MP-ALIPAY
						params.url = params.url + `&baidu=1`
						//#endif 

						if (this.vuex_user.type == '2' || this.vuex_user.type == '4') params.url =
							`${params.url}&superior=${this.vuex_user.pk_id}`;
						params.url = escape(params.url); //加密
					}
					return params;
				} else {
					return null;
				}
			}
		},
		methods: {
			$backToTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: this.duration
				});
			},
			// 客服
			$customer() {
				// #ifdef H5
				let phone = this.vuex_business.custom_tel;
				uniCall(phone);
				// #endif
			},
			// 分享
			$share() {
				this.$closePopup();
				// #ifdef H5
				this.shareVisible = true;
				// #endif
			},
			//打开分享选择弹框，可以选择分享到微信好友或者保存海报 (小程序端)
			$showSelectBox() {
				this.shareBoxVisible = true;
				if (this.prodInfo.logo) {
					let str = this.prodInfo.logo;
					if (this.prodInfo.logo.includes('http')) {
						str = this.prodInfo.logo.replace('http:', 'https:');
					}

					uniGetImageInfo(str).then(res1 => {

						// #ifdef MP-WEIXIN || MP-ALIPAY  || MP-BAIDU || MP-TOUTIAO
						this.productimgform = res1
						// #endif
						// #ifdef H5
						this.$resPost('DownloadPictures', {
							img: str
						}).then(({
							data
						}) => {

							this.productimgform = {
								...res1,
								path: `${this.vuex_businessObj.resquest}${data.img}`
							}
						})
						// #endif
					});
				}
			},
			$closePopup() {
				this.shareVisible = false;
				this.shareBoxVisible = false;
				this.posterVisible = false;
			},
			// 生成产品海报
			$createPoster() {
				this.$login('startCreatPoster', null).then(() => {
					this.startCreatPoster();
				});
			},
			startCreatPoster() {
				this.$closePopup();
				if (this.posterUrl) {
					this.posterVisible = true;
					return;
				}
				if (!this.posterParams) {
					this.$toast('未设置海报参数');
					return;
				}
				this.$loading();
				this.$getPosterRequest()
					.then(({
						data
					}) => {
						let posterUrl = `${this.vuex_businessObj.resquest}${data.url}`;
						if (!this.prodInfo.poster_url) {
							uniGetImageInfo(posterUrl).then(res => {
								this.codeimgform = res;
								this.$hide();
								this.drawcanvas();
							}).catch((err) => {
								this.$hide();
								this.posterVisible = false
							});
						} else {
							// 商品自己设置了海报
							this.posterUrl = posterUrl;
							this.$hide();
						}
						this.posterVisible = true;
					})
					.catch(() => {
						this.$hide();
						this.$toast('生成失败')
					});
			},
			// 开始画海报
			drawcanvas() {
				if (this.prodInfo.logo && !this.productimgform.path) {
					setTimeout(() => {
						this.drawcanvas()
					}, 300)
					return
				}
				this.$loading()
				let that = this;
				let allheight = 20;

				// uniapp canvasToTempFilePath这个方法支付宝不兼容，所以只能用支付宝原生
				// #ifdef MP-ALIPAY
				const ctx = my.createCanvasContext('codecanvas', this);
				// #endif

				// #ifdef MP-BAIDU
				const ctx = swan.createCanvasContext('codecanvas', this);
				// #endif

				// #ifndef MP-ALIPAY || MP-BAIDU
				const ctx = uni.createCanvasContext('codecanvas', this);
				// #endif

				ctx.setFillStyle('#ffffff');
				ctx.fillRect(0, 0, 375, 1200);
				let height = 0;
				if (this.prodInfo.logo) {
					height = (335 * this.productimgform.height) / this.productimgform.width;
					ctx.drawImage(this.productimgform.path, 20, allheight, 335,
						height); // 设置图片坐标及大小，括号里面的分别是（图片路径，x坐标，y坐标，width，height）
				}
				allheight = allheight + parseInt(height) + 30;
				// 小程序码
				let codeheight = (85 * this.codeimgform.height) / this.codeimgform.width;
				let maLX = 270
				ctx.drawImage(this.codeimgform.path, maLX, allheight, 85, codeheight);
				// 小程序码分销提示

				// #ifndef MP-ALIPAY
				let rightH = allheight + 80 + 24;
				// #endif
				// #ifdef  MP-ALIPAY
				let rightH = allheight + 80 + 34;
				// #endif
				if (this.vuex_user.nickname) {
					ctx.setFontSize(14);
					ctx.setFillStyle('#999999');
					ctx.setTextAlign('center')
					ctx.fillText(`${this.vuex_user.nickname}`, maLX + 42.5, rightH);
					rightH += 23;
					ctx.fillText('邀您抢优惠', maLX + 42.5, rightH);
					ctx.setTextAlign('left')
				}
				let leftH = allheight + 5
				ctx.setFontSize(19);
				//商品标题处理
				ctx.setFillStyle('#333333');
				// this.prodInfo.name
				let rowArr = this.canvasText(ctx, this.prodInfo.name, 210, 2);
				for (let b = 0; b < rowArr.length; b++) {
					ctx.fillText(rowArr[b], 20, leftH + b * 24);
				}
				leftH = leftH + 2 * 24;
				// 价格
				leftH += 47;
				ctx.setFillStyle('#b93e37');
				ctx.setFontSize(17);
				ctx.fillText(`￥`, 20, leftH);
				let x = ctx.measureText('￥').width;
				ctx.setFontSize(26);
				// #ifdef  MP-BAIDU
				ctx.fillText(`${this.prodInfo[this.stockName][0].amount}`, 30 + x, leftH);
				// #endif 

				// #ifndef MP-BAIDU
				ctx.fillText(`${this.prodInfo[this.stockName][0].amount}`, 20 + x, leftH);
				// #endif 
				leftH += 29;
				ctx.setFillStyle('#999999');
				ctx.setFontSize(15);
				let str = '小程序码'
				// #ifdef H5
				str = '二维码'
				// #endif
				// #ifndef MP-ALIPAY
				ctx.fillText(`长按识别${str}访问`, 20, leftH);
				// #endif
				// #ifdef  MP-ALIPAY
				ctx.fillText(`点击识别${str}访问`, 20, leftH);
				// #endif
				ctx.save(); //保存
				allheight = leftH > rightH ? leftH : rightH;
				allheight += 20;
				ctx.draw(false, () => {
					// #ifndef MP-ALIPAY

					uni.canvasToTempFilePath({
							quality: 1,
							height: allheight,
							canvasId: 'codecanvas',
							success: function(res) {
								// 在H5平台下，tempFilePath 为 base64
								that.posterUrl = res.tempFilePath;
								that.$hide()
							},
							fail: err => {
								that.$hide()
							}
						},
						this
					);
					//  #endif 

					// #ifdef MP-ALIPAY
					// 支付宝只适应png跟jpg图 其他图会出问题
					ctx.toTempFilePath({
							quality: 1,
							height: allheight,
							success: function(res) {
								that.posterUrl = res.apFilePath
								that.$hide()
							},
							fail: err => {
								that.$hide()
							}
						},

					);
					//  #endif 

				}); //绘制
			},

			// #ifdef MP-ALIPAY
			saveImageToPhotosAlbum() {
				uniModal({
					title: '提示',
					content: '是否下载海报'
				}).then(() => {
					my.saveImageToPhotosAlbum({
						filePath: this.posterUrl,
						success: () => {
							this.$toast('海报下载成功')
						},
						fail: () => {
							this.$toast('海报下载失败')
						}
					});
				})

			},
			//  #endif 
			/*
			 * 注意要先设置好字体大小先
			 * context:canvas 实例对象
			 * str:总文字
			 * lineW:每行限制的宽度
			 * rowNum: 行数限制
			 * return: arr:每一行文字组成的数组
			 */
			canvasText(context, str, lineW, rowNum) {
				let chr = str.split(''); // 每一个字符串为一个元素组成数组
				let temp = ''; // 下一行的文本
				var row = []; // 每一行文本为一个元素组成数组
				for (let a = 0; a < chr.length; a++) {
					if (context.measureText(temp).width < lineW) {
						temp += chr[a];
					} else {
						a--; //这里添加了a-- 是为了防止字符丢失
						row.push(temp);
						temp = '';
					}
				}
				row.push(temp); //将最后一行文本加上
				if (row.length > rowNum) {
					// 只要三行,超出省略号
					let rowCut = row.slice(0, rowNum);
					var rowPart = rowCut[rowNum - 1]; // 旧的最后一行的文本
					var test = ''; // 新的最后一行文本
					for (let a = 0; a < rowPart.length; a++) {
						if (context.measureText(test).width < lineW - 20) {
							test += rowPart[a];
						} else {
							break;
						}
					}
					test += '...';
					rowCut.splice(rowNum - 1, 1, test);
					row = rowCut;
				}
				return row;
			},
			// 获取海报+小程序 / 小程序码
			$getPosterRequest() {
				let params = {
					...this.posterParams,
					appid: this.vuex_business.appid
					// openid: this.vuex_user.small_routine
				};
				return this.$resPost('SmallProgramQRCode', params);
			}
		},
		watch: {
			showBackTop(nVal, oVal) {
				// 当组件的显示与隐藏状态发生跳变时，修改组件的层级和不透明度
				// 让组件有显示和消失的动画效果，如果用v-if控制组件状态，将无设置动画效果
				if (this.hasTop && nVal) {
					this.opacity = 1;
				} else {
					this.opacity = 0;
				}
			}
		}
	};
</script>
<style lang="scss" scoped>
	.sww-sidebar-box {
		width: 80rpx;
		min-height: 70rpx;
		position: fixed;
		opacity: 0.7;
		z-index: 999; // 因为首页的每个组件都有z-index，所以这里不加的话，首页的内容会遮挡它

		.sww-sidebar-item {
			width: 100%;
			height: 80rpx;
			color: #ffffff;
			background-color: var(--color);
			display: flex;
			align-items: center;
			justify-content: center;
			transition: opacity 0.3s;
			border-radius: 50%;
			margin-bottom: 20rpx;

			&:last-child {
				margin-bottom: 0;
			}
		}
	}

	.h5-show-tips {
		width: 400rpx;
		height: 60rpx;
		background-color: #ffffff;
		position: absolute;
		top: 40rpx;
		right: 24rpx;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		&::before {
			content: '';
			border: 18rpx solid transparent;
			position: absolute;
			top: 1rpx;
			right: 20rpx;
			border-bottom-color: #ffffff;
			border-right-color: #ffffff;
			transform: translate(0, -100%);
		}
	}

	.share-select-box {
		width: 100%;

		.share-select-list {
			width: 100%;
			display: flex;

			.share-select-item {
				flex: 1;
				height: 300rpx;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.share-select-icon {
					width: 90rpx;
					height: 90rpx;
					color: #fff;
					background-color: #07c160;
					border-radius: 50%;
					margin-bottom: 20rpx;
					box-sizing: border-box;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 50rpx;
				}

				&:last-child {
					.share-select-icon {
						background-color: #1989fa;
					}
				}
			}
		}

		.share-select-cancel {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-top: 1rpx solid #cccccc;
			box-sizing: content-box;
		}
	}

	.post_main {
		height: 100%;
		padding: 40rpx 0;
		display: flex;
		align-items: center;

		.poster-box {
			width: 600rpx;
			max-height: 100%;
			overflow-y: auto;
			// display: flex;
			// flex-direction: column;
			// justify-content: center;
			// align-items: center;
			border-radius: 12rpx;
			margin: auto;
			background-color: #fff;

			.poster-img {
				width: 100%;
				border-radius: 12rpx;
			}

			.poster-text {
				font-size: 28rpx;
				color: #333;
				line-height: 100rpx;
				text-align: center;
			}
		}
	}


	/* 	 #ifdef MP-ALIPAY  */
	::v-deep .share-select-item .u-icon__icon {
		font-size: 70rpx !important;
		color: #5199FF !important;
		margin-bottom: 20rpx;
	}

	/* #endif  */
</style>
